package com.tanhua.app.Service;

import com.tanhua.api.UserInfoApi;

import com.tanhua.api.VoiceApi;
import com.tanhua.app.exception.BusinessException;
import com.tanhua.app.interceptor.UserThreadLocal;
import com.tanhua.autoconfig.template.OssTemplate;
import com.tanhua.model.mongo.Voice;
import com.tanhua.model.pojo.UserInfo;
import com.tanhua.model.vo.ErrorResult;
import com.tanhua.model.vo.VoiceVo;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

@Service
public class PeachblossomService {
    @DubboReference
    private VoiceApi voiceApi;
    @Autowired
    private OssTemplate ossTemplate;
    @Autowired
    private RedisTemplate redisTemplate;
    @DubboReference
    private UserInfoApi userInfoApi;

    //保存桃花传音
    public void save(MultipartFile soundFile) throws IOException {

        Voice voice = new Voice();
        voice.setCreated(System.currentTimeMillis());
        voice.setState(0);
        voice.setUserId(UserThreadLocal.getid());
        String url = ossTemplate.upload(soundFile.getOriginalFilename(), soundFile.getInputStream());
        voice.setVoiceUrl(url);
        voiceApi.save(voice);


    }

    //获取桃花传音
    public VoiceVo getVoice() {
        //存值，同时设置过期时间
        Integer count = (Integer) redisTemplate.opsForValue().get("remainingTimes" + UserThreadLocal.getid());
        if (count == null) {
            redisTemplate.opsForValue().set("remainingTimes" + UserThreadLocal.getid(), 9, 1, TimeUnit.DAYS);
            count = 9;
        } else {
            count = count - 1;
            if (count < 0) {
                throw new BusinessException(ErrorResult.error());
            }
            redisTemplate.opsForValue().set("remainingTimes" + UserThreadLocal.getid(), count, 0);
        }
        Voice voice = voiceApi.getVoice();
        if (voice == null) {
            return null;
        }
        UserInfo userInfo = userInfoApi.selectById(voice.getUserId());
        VoiceVo voiceVo = new VoiceVo();
        voiceVo.setNickname(userInfo.getNickname());
        voiceVo.setAge(userInfo.getAge());
        voiceVo.setAvatar(userInfo.getAvatar());
        voiceVo.setGender(userInfo.getGender());
        voiceVo.setRemainingTimes(count+1);
        voiceVo.setSoundUrl(voice.getVoiceUrl());
        voiceVo.setId(Integer.parseInt(userInfo.getId().toString()));
       voiceApi.updatestate(voice.getId());
        return voiceVo;
    }
}
